const dgram = require('dgram')
const sock = dgram.createSocket('udp4')

const MY_PORT = 10010 // A 自己监听的端口
// const PEER_HOST = '127.0.0.1' // B 的地址
// const PEER_PORT = 5001 // B 监听的端口

sock.on('message', (msg, rinfo) => {
  console.log(`[A<-] ${rinfo.address}:${rinfo.port} -> ${JSON.stringify(msg)}`)
  const buf = Buffer.from(msg)
  sock.send(buf, rinfo.port, rinfo.address)
})

sock.on('error', (err) => {
  console.error('A socket error:', err)
  sock.close()
})

sock.bind(MY_PORT, () => {
  console.log(`A listening on ${MY_PORT}`)
  // setInterval(() => {
  //   const buf = Buffer.from(`hello from A @${Date.now()}`)
  //   sock.send(buf, PEER_PORT, PEER_HOST)
  //   console.log(`[A->] ${PEER_HOST}:${PEER_PORT} <- ${buf}`)
  // }, 1000)
})
